﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.Web;

namespace FoundationLib.Web.Mvc
{
	public static class HtmlPrefixScopeHelper
	{
		private const string QUEUE_KEY = "_htmlPrefixScopeHelper_identifiers_";

		public static IDisposable BeginCollectionItem(this HtmlHelper helper, string collectionName)
		{
			FieldIdentifierQueue queue = new FieldIdentifierQueue(helper.ViewContext.HttpContext, collectionName, QUEUE_KEY);
			string fieldIdentifier = queue.Count > 0 ? queue.Dequeue() : Guid.NewGuid().ToString();

			TagBuilder tb = new TagBuilder("input");
			tb.MergeAttribute("type", "hidden");
			tb.MergeAttribute("autocomplete", "off");
			tb.MergeAttribute("name", String.Format("{0}.index", collectionName));
			tb.MergeAttribute("value", helper.Encode(fieldIdentifier));

			helper.ViewContext.Writer.WriteLine(tb.ToString(TagRenderMode.SelfClosing));

			return new HtmlPrefixScope(helper.ViewData.TemplateInfo, String.Format("{0}[{1}]", collectionName, fieldIdentifier));
		}

	}
}
